// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator;

@ccclass
export default class auto_node_size extends cc.Component {

    spr: cc.Sprite = null;
    width: number = 0;
    height: number = 0;

    onLoad() {
        this.width = this.node.width;
        this.height = this.node.height;

        this.spr = this.node.getComponent(cc.Sprite);
        if (this.spr == null) {
            console.error("auto_node_size节点不是cc.Sprite节点 : " + this.node.name);
        }

        this.spr.sizeMode = cc.Sprite.SizeMode.RAW;

        this.node.on("size-changed", () => {
            if (this.node.width != this.width || this.node.height != this.height) {
                this.auto_node_size();
            }
        });
    }

    start() {

    }

    update(dt) {

    }

    /**
     *    自动调整节点 到 合适尺寸  (等比例 缩放)
     */
    auto_node_size() {
        let w = this.width;
        let h = this.height;
        let nw = this.node.width;
        let nh = this.node.height;

        let nbili = nw / nh;  // 节点宽高比
        let mbili = w / h;

        if (nbili > mbili) { //// 节点 宽度 比较大
            this.node.width = w;
            this.node.height = w / nw * nh;
        } else {  ////// 节点高度 比较大
            this.node.height = h;
            this.node.width = h / nh * nw;
        }
    }
}


